package com.yang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.dao.entity.UserDO;
import com.yang.dao.mapper.UserMapper;
import com.yang.dto.req.UserPageQueryReqDTO;
import com.yang.dto.resp.UserPageQueryRespDTO;
import com.yang.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户业务实现层
 * 作者：孤城暖阳y
 * 开发时间：2025-02-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final UserMapper userMapper;

    @Override
    public IPage<UserPageQueryRespDTO> pageQueryUser(UserPageQueryReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(
                        Objects.nonNull(requestParam.getUserId()), UserDO::getUserId, requestParam.getUserId())
                .like(
                        Objects.nonNull(requestParam.getUserNickname()), UserDO::getUserNickname, requestParam.getUserNickname())
                .like(
                        Objects.nonNull(requestParam.getUserAccount()), UserDO::getUserAccount, requestParam.getUserAccount())
                .eq(
                        Objects.nonNull(requestParam.getUserPhone()), UserDO::getUserPhone, requestParam.getUserPhone())
                .between(
                        Objects.nonNull(requestParam.getStartTime()) && Objects.nonNull(requestParam.getEndTime()),
                        UserDO::getCreateTime,
                        requestParam.getStartTime(), requestParam.getEndTime()
                );
        // 执行查询
        IPage<UserDO> page = userMapper.selectPage(requestParam, queryWrapper);
        // 转换为响应对象
        return page.convert(each -> BeanUtil.toBean(each, UserPageQueryRespDTO.class));
    }

    @Override
    public void deleteUser(Long userId) {
        if (Objects.isNull(userMapper.selectById(userId))) {
            throw new RuntimeException("用户不存在");
        }
        userMapper.deleteById(userId);
    }
}
